package reader.contorller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class KaptchaControeller {
     @Autowired
    private Producer producer;

     @GetMapping("/api/verify_code")
     public void createCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
         resp.setDateHeader("Expires", 0);
         // 不缓存
         resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
         resp.setHeader("Cache-Control", "post-check=0, pre-check=0");
         resp.setHeader("Pragma", "no-cache");
         resp.setContentType("image/jpeg");

         String capText = producer.createText();
         req.getSession().setAttribute("capText", capText);
         BufferedImage image = producer.createImage(capText);

         ServletOutputStream outputStream = resp.getOutputStream();
         ImageIO.write(image,"png",outputStream);
         outputStream.flush();
         outputStream.close();
     }
}
